<template>
  <div class="work-voucher-info">
    <el-form ref="form" :model="formData" label-width="150px">
      <el-row>
        <el-col :span="24">
          <div
            class="work-content"
            v-for="(item, index) in formData.workInfo"
            :key="index"
          >
            <div class="work-item">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    :label="$t(' 服务类型：')"
                    :prop="`workInfo.${index}.productCode`"
                    :rules="rules.productCode"
                  >
                    <el-select
                      :disabled="readonly"
                      @change="chooseData($event, index)"
                      v-model="item.productCode"
                      :placeholder="$t('请选择服务类型')"
                    >
                      <el-option
                        v-for="i in productList"
                        :key="i.value"
                        :label="i.label"
                        :value="i.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('凭证渠道：')" prop="voucherChannel">
                    <el-input
                      :disabled="readonly"
                      v-model="item.voucherChannel"
                      maxlength="20"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item :label="$t('凭证样张：')">
                  <zczy-upload
                    :headers="headers"
                    :business="$config.ossBusiness"
                    :module="$config.ossModule"
                    :env="$config.ossEnv"
                    :action="actionUrl"
                    v-if="!readonly"
                    :show-file-list="false"
                    :limit="10"
                    :on-success="
                      (response, file, fileList) =>
                        handleAvatarSuccess(response, file, fileList, index)
                    "
                    :before-upload="beforeUpload"
                    :on-error="onError"
                    accept="*"
                    style="display: inline-block"
                  >
                    <el-button
                      v-if="item.files.length < 10"
                      type="primary"
                      size="small"
                      style="margin-left: 12px"
                      >{{ $t('上传') }}</el-button
                    >
                  </zczy-upload>
                  <div class="work-upload-files">
                    <div
                      class="file"
                      v-for="(it, idx) in item.files"
                      :key="idx"
                    >
                      <a @click="downloadFile(it)" class="">{{
                        it.fileName
                      }}</a>
                      <i
                        class="el-icon-close"
                        @click="deleteFile(index, idx)"
                        v-if="!readonly"
                      ></i>
                    </div>
                  </div>
                </el-form-item>
              </el-row>
            </div>
            <img
              style="cursor: pointer"
              src="@/assets/images/del_icon.png"
              width="16px"
              height="18px"
              v-if="!readonly"
              @click="delWork(index)"
            />
          </div>
          <el-button
            type="text"
            class="el-icon-plus"
            @click="handleAdd"
            v-if="
              !readonly && formData.workInfo && formData.workInfo.length < 5
            "
            >{{ $t('添加') }}</el-button
          >
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import nonStandardService from '@/services/nonStandardService'
export default {
  name: 'workVoucherInfoList',
  props: {
    detail: {
      type: Object,
      default: () => {
        return {}
      },
    },
    value: {},
    disabled: Boolean,
    parameter: {
      type: Object,
      default: () => {
        return {}
      },
    },
    definitionId: {},
  },
  data() {
    return {
      formData: {
        workInfo: [],
      },
      rules: {
        productCode: [
          {
            required: true,
            message: this.$t('请选择服务类型'),
            trigger: 'change',
          },
        ],
      },
      productList: [],
      actionUrl:
        process.env.VUE_APP_BASE_API +
        '/contract-client-web/system/file/uploadFile',
      headers: {
        ucSsoTokenId: localStorage.getItem('token'),
        ucSystemFlag: 31,
        from: 'saas',
      },
      fileBaseUrl: 'https://img.zczy56.com/',
      readonly: false,
    }
  },
  created() {
    this.readonly = Boolean(this.$route.query.readonly)
    this.projectSelect()
    if (this.value) {
      this.setData()
    }
  },
  methods: {
    // 查询服务类型
    projectSelect() {
      nonStandardService
        .queryServiceTypeInfo({ ecologyCode: 'WMS', eventState: 1 })
        .then((res) => {
          if (res.code == 200) {
            this.productList =
              res.data.amsPriceEventInfos &&
              res.data.amsPriceEventInfos.map((it) => {
                return {
                  ...it,
                  label: it.eventCode + it.eventName,
                  value: it.eventCode,
                }
              })
          }
        })
    },
    // 新增作业凭证
    handleAdd() {
      this.formData.workInfo.push({ files: [] })
    },
    // 删除作业凭证
    delWork(index) {
      this.formData.workInfo.splice(index, 1)
    },
    // 选择服务类型
    chooseData(val, index) {
      let flag = this.formData.workInfo.some(
        (it, idx) => index != idx && it.productCode == val
      )
      if (flag) {
        this.$message.error(this.$t('服务类型不可重复'))
        this.formData.workInfo[index].productCode = null
        return
      }
      let info = this.productList.find((it) => it.value == val) || {}
      this.formData.workInfo[index].productsName = info.eventName
    },
    setData() {
      this.formData.workInfo = JSON.parse(this.value) || []
    },
    getData() {
      let workVoucherInfos = (this.formData.workInfo || []).map((it) => {
        return {
          ...it,
          files: (it.files || []).map((item) => {
            return {
              fileUrl: item.fileUrl,
              fileName: item.fileName,
              fileSize: item.fileSize,
            }
          }),
        }
      })
      return workVoucherInfos
    },
    validator() {
      return this.$refs.form.validate()
    },
    // 文件上传
    handleAvatarSuccess(res, file, fileList, index) {
      this.formData.workInfo[index].files.push({
        fileUrl: res.name,
        fileName: res.realName,
        fileReviewUrl: res.previewUrl,
        fileSize: res.size,
      })
    },
    // 删除文件
    deleteFile(index, idx) {
      this.formData.workInfo[index].files.splice(idx, 1)
    },
    // 文件限制
    beforeUpload(file) {
      const isLt20M = file[0].size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error(this.$t('上传文件大小不能超过20M!'))
        return false
      }
      return isLt20M
    },
    onError(err) {
      this.$message.error(err.msg)
    },
    downloadFile(item) {
      let url = item.fileReviewUrl || item.fileUrl
      if (url.startsWith('http') || url.startsWith('https')) {
        window.open(url)
      } else {
        window.open('https://img.zczy56.com/' + url)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.work-voucher-info {
  width: 100%;
  .work-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    width: 95%;
    min-width: 460px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;
    .work-item {
      width: 90%;
      .work-upload-files {
        margin-top: 12px;
        display: flex;
        flex-wrap: wrap;
        .file {
          margin-right: 10px;
          cursor: pointer;
        }
        .el-icon-close {
          cursor: pointer;
          margin-left: 24px;
        }
      }
    }
  }
}
</style>
